package org.ccay.web.support.internal.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.server.IAfterStartupHandler;
import org.ccay.core.server.StartupEventArgs;
import org.ccay.core.util.StringUtil;
import org.ccay.web.support.internal.IHostDomainHandler;

/**
 * 域名白名单处理
 * 
 */
@Named
public class HostDomainHandler implements IHostDomainHandler, IAfterStartupHandler {

	private static final ILogger logger = CcayLoggerFactory.getLogger(HostDomainHandler.class);

	/**
	 * 域名白名单
	 */
	private Set<String> hostWhiteList = new HashSet<String>();

	// 
//	@Inject
//	private IRegistryQueryService registryQueryService;

	public void execute(Object sender, StartupEventArgs args) throws ApplicationException {
		updateHostWhiteList();
	}

	/**
	 * TODO 获取域白名单数据字典
	 * 
	 * 
	 * @since 2015年8月18日
	 */
	public void updateHostWhiteList() {
		// 界面删除某个域白名单,如果不clear就会一直保留在缓存中
		hostWhiteList.clear();
		
		// 添加域名到白名单中，域名可以从其他配置中获取
		hostWhiteList.add(".ccay.org");
		hostWhiteList.add(".greenccay.org");
		hostWhiteList.add(".vmall.com");
		hostWhiteList.add(".hisilicon.com");

		//TODO "App.Security.HostWhiteList
//		RegistryVO queryRegistry = registryQueryService.findRegistryByPathNoAssert("App.Security.HostWhiteList", true);
//
//		if (null != queryRegistry && StringUtils.isNotEmpty(queryRegistry.getValue())) {
//			for (String value : queryRegistry.getValue().split(",")) {
//				hostWhiteList.add(value);
//			}
//		}
	}

	public boolean containsHostDomain(String url) {
		return true;
		//TODO white list
//		logger.debug("Before to check url : " + url);
//		String host = null;
//		try {
//			host = new URL(url).getHost();
//			logger.debug("Check url and Get the host is : {0}", host);
//		} catch (MalformedURLException e) {
//			logger.debug("Get host error.", e);
//		}
//		if (StringUtil.isNullOrEmpty(host)) {
//			return true;
//		}
//		// 获取返回路径的域名
//		for (String validHost : hostWhiteList) {
//			//校验域名结尾,避免绕过安全校验 
//			if (host.endsWith(validHost)) {
//				logger.debug("Found host {0} is in host white list!", host);
//				return true;
//			}
//		}
//		logger.debug("Can not found host {0} in host white list.", host);
//		return false;
	}

	public Set<String> getHostWhiteList() {
		return hostWhiteList;
	}

	public int getOrder() {
		return 70;
	}

}
